/*
 * CSocketsEngine.cpp
 *
 *  Created on: 2009-5-10
 *      Author: xiayang
 */

#include "CSocketsEngine.h"


void CSocketsEngine::ConnectSocket(void)
	{
	TInt err = iSocketServer.Connect();
	if (err != KErrNone && err != KErrAlreadyExists)
		{
		User::Leave(err);
		}
	
	TUint numProtocols;
	err = iSocketServer.NumProtocols(numProtocols);
	User::LeaveIfError(err);
	
	_LIT(KProtocol,"IrTinyTP");
	TProtocolName protocolName(KProtocol);
	err = iSocketServer.FindProtocol(protocolName,iProtocolInfo);
	User::LeaveIfError(err);
	}


void CSocketsEngine::OpenSocket(void)
	{
	TInt err;
	
	err = iSocket.Open(iSocketServer, iProtocolInfo.iAddrFamily,
iProtocolInfo.iSockType, iProtocolInfo.iProtocol);
	
	if (err != KErrNone && err != KErrAlreadyExists)
		{
		User::Leave(err);
		}
	}


void CSocketsEngine::ConnectServer(void)
	{
	const TUint KPortNumber = 0x02;
	iIrdaSockAddr.SetPort(KPortNumber);
	iSocket.Bind(iIrdaSockAddr);
	
	const TUint KSizeOfListenQueue = 1;
	iSocket.Listen(KSizeOfListenQueue);
	iServiceSocket.Open(iSocketServer);
	
	iSocket.Accept(iServiceSocket, iStatus);
	iState = EAccepting;
	SetActive();
	}


void CSocketsEngine::ConnectClient(void)
	{
	const TUint KNumOfDevicesToDiscover = 1;
	const TUint KPortNumber = 0x02;
	
	TInt err;
	THostName hostname;
	
	TPckgBuf<TUint> buf(KNumOfDevicesToDiscover);
	iSocket.SetOpt(KDiscoverySlotsOpt, KLevelIrlap, buf);
	
	err = iHostResolver.Open(iSocketServer, iProtocolInfo.iAddrFamily,
iProtocolInfo.iProtocol);
	
	User::LeaveIfError(err);
	
	iState = EDiscovering;
	iHostResolver.GetByName(hostname, iNameEntry, iStatus);
	SetActive();
	
	iHostResolver.Close();
	
	iIrdaSockAddr = TIrdaSockAddr(iNameEntry().iAddr);
	iIrdaSockAddr.SetPort(KPortNumber);
	iState = EConnecting;
	iSocket.Connect(iIrdaSockAddr, iStatus);
	SetActive();
	}


void CSocketsEngine::SendL(const TDesC &aData)
	{
	if (iState == ESending)
		{
		}
	}
